package com.yiqi.zhiyuan.feature.certification.view;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.widget.PowerfulEditText;
import com.suozhang.framework.widget.dialog.ActionSheetDialog;
import com.suozhang.framework.widget.dialog.OnOperItemClickL;
import com.yiqi.zhiyuan.R;
import com.yiqi.zhiyuan.entity.bo.UploadCertificatesInfo;
import com.yiqi.zhiyuan.entity.vo.CarVO;
import com.yiqi.zhiyuan.feature.certification.contract.VehicleContract;
import com.yiqi.zhiyuan.feature.certification.dependencies.vehicle.DaggerVehicleComponent;
import com.yiqi.zhiyuan.feature.certification.dependencies.vehicle.VehiclePresenterModule;
import com.yiqi.zhiyuan.feature.certification.view.adapter.UploadCertificatesAdapter;
import com.yiqi.zhiyuan.framework.DataServer;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.yiqi.zhiyuan.feature.certification.view.UserInformationActivity.CAR_COLOR;
import static com.yiqi.zhiyuan.feature.certification.view.UserInformationActivity.CAR_MODEL;

public class AddVehicleActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener,
        BaseQuickAdapter.OnItemChildClickListener, OnOperItemClickL, VehicleContract.View, Toolbar.OnMenuItemClickListener {

    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.edt_car_brand_number)
    PowerfulEditText mEdtCarBrandNumber;
    @BindView(R.id.edt_car_brand)
    TextView mEdtCarBrand;
    @BindView(R.id.edt_car_model)
    TextView mEdtCarModel;
    @BindView(R.id.edt_car_color)
    TextView mEdtCarColor;
    @BindView(R.id.rv_upload_list)
    RecyclerView mRvUploadList;
    private ActionSheetDialog dialog;
    private List<LocalMedia> selectList;
    private int mPosition;
    private boolean isFirst = false;
    private String mVehicleId=null;


    private String mBrandStr;
    private String mModelStr;
    private CarVO mCarVO;

    UploadCertificatesAdapter mAdapter;
    List<UploadCertificatesInfo> mCertificatesInfos;

    @Inject
    VehicleContract.Presenter mPresenter;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_add_vehicle;
    }

    @Override
    protected void initInjector() {
        DaggerVehicleComponent.builder().vehiclePresenterModule(new VehiclePresenterModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {

        mToolbar.inflateMenu(R.menu.menu_commit);
        initToolBar(mToolbar, getString(R.string.upload_certificates_title), true, true);
        initAdapter();


        final String[] stringItems = {"拍照", "从手机相册选择"};
        dialog = new ActionSheetDialog(this, stringItems, null);
        dialog.isTitleShow(false);
        dialog.setOnOperItemClickL(this);
    }

    private void initAdapter() {
        mCertificatesInfos = DataServer.getUploadTypeAdd();
        mRvUploadList.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new UploadCertificatesAdapter();
        mAdapter.bindToRecyclerView(mRvUploadList);
        mAdapter.setNewData(mCertificatesInfos);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnItemChildClickListener(this);
    }

    @Override
    protected void initData() {
        isFirst = this.getIntent().getBooleanExtra("is_first", false);
        mCarVO = (CarVO) this.getIntent().getSerializableExtra("car_info");
        if (!isFirst && mCarVO != null) {
            setCarData(mCarVO);
        }
    }

    /**
     * 设置汽车数据
     */
    private void setCarData(CarVO data) {
        mVehicleId=data.getId();
        mEdtCarBrandNumber.setText(data.getCarNo());
        mBrandStr = data.getCarName();
        mModelStr = data.getCarModelNo();
        mEdtCarColor.setText(data.getCarColor());
        mEdtCarModel.setText(mBrandStr + "-" + mModelStr);

        List<UploadCertificatesInfo> uploadCertificatesInfos=new ArrayList<>();
        for (int i = 0; i < mCertificatesInfos.size(); i++) {
            UploadCertificatesInfo info = mCertificatesInfos.get(i);

            if (info.getName().equals("travelPositive")) {
                info.setImgUrl(data.getTravelPositive());
            }
            if (info.getName().equals("operationPositive")) {
                info.setImgUrl(data.getOperationPositive());
            }
            if (info.getName().equals("netCarPositive")) {
                info.setImgUrl(data.getNetCarPositive());
            }
            if (info.getName().equals("carPersonPositive")) {
                info.setImgUrl(data.getCarPersonPositive());
            }
            uploadCertificatesInfos.add(info);
        }
        mAdapter.setNewData(uploadCertificatesInfos);
    }

    @Override
    protected void initEvent() {
        mToolbar.setOnMenuItemClickListener(this);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        mPosition = position;
        dialog.show();
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        UploadCertificatesInfo uploadCertificatesInfo = mAdapter.getItem(position);
        uploadCertificatesInfo.setImgUrl(null);
        mCertificatesInfos.set(position, uploadCertificatesInfo);
        mAdapter.setData(position, uploadCertificatesInfo);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (resultCode == -1) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    for (int i = 0; i < selectList.size(); i++) {
                        UploadCertificatesInfo info = mCertificatesInfos.get(mPosition);
                        info.setImgUrl(selectList.get(i).getCutPath());
                        mCertificatesInfos.set(mPosition, info);
                        if (mAdapter != null) {
                            mAdapter.setData(mPosition, info);
                        }
                    }

                    break;
                case CAR_MODEL:
                    if (data != null) {
                        mBrandStr = data.getStringExtra("brand");
                        mModelStr = data.getStringExtra("model");
                        mEdtCarModel.setText(mBrandStr + "-" + mModelStr);
                    }
                    break;

                case CAR_COLOR:
                    String color = data.getStringExtra("color");
                    mEdtCarColor.setText(color);
                    break;
            }
        }
    }

    @Override
    public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (position) {
            case 0:
                PictureSelector.create(this)
                        .openCamera(PictureMimeType.ofImage())
                        .theme(R.style.picture_default_style)
                        .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                        .previewImage(true)// 是否可预览图片
                        .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                        .enableCrop(true)// 是否裁剪
                        .compress(true)// 是否压缩
                        .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                        .isGif(false)// 是否显示gif图片
                        .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
            case 1:
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .theme(R.style.picture_default_style)
                        .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                        .previewImage(true)// 是否可预览图片
                        .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                        .isCamera(false)
                        .enableCrop(true)// 是否裁剪
                        .compress(true)// 是否压缩
                        .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                        .isGif(false)// 是否显示gif图片
                        .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                        .scaleEnabled(true)
                        .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                break;

        }

        if (dialog != null) {
            dialog.dismiss();
        }
    }

    @Override
    public void showInsertVehicleSuccess() {
        finish();

    }

    @Override
    public void showInsertVehicleError(String errorMsg) {
        showMsg(errorMsg);
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        mPresenter.doInsertVehicle(
                mCertificatesInfos,
                mEdtCarBrandNumber.getText().toString().trim(),
                mBrandStr,
                mModelStr,
                mEdtCarColor.getText().toString().trim(),
                isFirst?null:mVehicleId
        );
        return false;
    }


    @OnClick({R.id.edt_car_model, R.id.edt_car_color})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.edt_car_model:
                Intent colorModel = new Intent(this, CityPickerActivity.class);
                startActivityForResult(colorModel, CAR_MODEL);
                break;
            case R.id.edt_car_color:
                Intent colorIntent = new Intent(this, SelectColorActivity.class);
                startActivityForResult(colorIntent, CAR_COLOR);
                break;
        }
    }


}
